//
//  ZCMVPlayerViewController.m
//  VoiceMusic
//
//  Created by dllo on 15/10/22.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCMVPlayerViewController.h"
#import "ZCMVPlayerTableViewCell.h"
#import "ZCMVPlayModel.h"
#import "ZCAFNetWork.h"
#import "ZCBaseLabel.h"
#import "ZCPlayMusicTool.h"
#import <AVFoundation/AVFoundation.h>
#import <UIImageView+WebCache.h>
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ZCMVPlayerViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) UITableView *MVTableView;
@property (nonatomic, strong) NSMutableArray *MVArr;
@property (nonatomic, strong) AVPlayer *player;//播放器对象
@property (nonatomic, strong) AVPlayerLayer *layer;
@property (nonatomic, assign) BOOL isplay;
@property (nonatomic, assign) BOOL isFull;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) ZCBaseLabel *introducelabel;
@property (nonatomic, strong) ZCBaseLabel *videoNameLabel;
@property (nonatomic, strong) UIButton *fullButton;
@property (nonatomic, strong) UIImageView *placeImageView;
@end

@implementation ZCMVPlayerViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillAppear:animated];
}
#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.MVArr = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTableView];
    [self createTableViewData];
    
    //返回
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark 返回
- 	(void)returnClick:(UIBarButtonItem *)button
{
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    UIView *view= (UIView *) [window.rootViewController.view viewWithTag:9999];
    view.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark 创建视图
- (void)createTableView
{
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH / 16 * 9)];
    [self.view addSubview:self.playView];
    
    self.placeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"50"]];
    [self.playView addSubview:self.placeImageView];
    self.placeImageView.frame = CGRectMake(0, 0, WIDTH, WIDTH / 16 * 9);
    
    // 创建播放层
    self.layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.layer.frame = CGRectMake(0, 0, WIDTH, WIDTH / 16 * 9);
    [self.playView.layer addSublayer:self.layer];
    // 默认状态
    self.isplay = YES;
    self.isFull = YES;
    // 创建播放相关按钮
    [self createplayer];
    // 创建tableView
    self.MVTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, WIDTH / 16 * 9, WIDTH, HEIGHT - 64 - WIDTH / 16 * 9) style:UITableViewStylePlain];
    [self.view addSubview:self.MVTableView];
    // 头视图
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 70)];
    [self.view addSubview:self.headView];
    self.MVTableView.tableHeaderView = self.headView;
    // 代理
    self.MVTableView.dataSource = self;
    self.MVTableView.delegate = self;
    self.MVTableView.emptyDataSetDelegate = self;
    self.MVTableView.emptyDataSetSource = self;
    self.MVTableView.rowHeight = 100;
    // 片名
    self.videoNameLabel = [[ZCBaseLabel alloc] initWithFrame:CGRectMake(20, 5, WIDTH - 40, 40)];
    [self.headView addSubview:self.videoNameLabel];
    NSString *videoName = [NSString stringWithFormat:@"%@ - %@",self.videoName,self.singerName];
    self.videoNameLabel.text = videoName;
    self.videoNameLabel.font = [UIFont systemFontOfSize:18];
    // 介绍
    self.introducelabel = [[ZCBaseLabel alloc] initWithFrame:CGRectMake(20, 45, WIDTH - 40, 20)];
    self.introducelabel.text = self.introduce;
    [self.headView addSubview:self.introducelabel];
    self.introducelabel.font = [UIFont systemFontOfSize:14];
}
#pragma mark 创建视频需要的按钮
- (void)createplayer
{
    // 播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playView addSubview:self.playButton];
    [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-1"] forState:UIControlStateNormal];
    self.playButton.frame = CGRectMake(5, 175, 35, 35);
    // 播放
    [self.playButton addTarget:self action:@selector(PlayMV:) forControlEvents:UIControlEventTouchUpInside];
    // 全屏按钮
    self.fullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playView addSubview:self.fullButton];
    [self.fullButton setImage:[UIImage imageNamed:@"iconfont-fullscreen"] forState:UIControlStateNormal];
    self.fullButton.frame = CGRectMake(WIDTH - 45, 175, 35, 35);
    // 全屏
    [self.fullButton addTarget:self action:@selector(full:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark 播放实现
- (void)PlayMV:(UIButton *)button
{
    // 判断现在的状态,改变按钮
    if (self.isplay) {
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting-2"] forState:UIControlStateNormal];
        // 播放
        [self.player play];
        
        //外面的歌曲停止播放
        [[ZCPlayMusicTool sharePlay].player pause];
        [ZCPlayMusicTool sharePlay].isplay = NO;
        //点击返回的时候判断播放按钮的状态
        [[NSNotificationCenter defaultCenter] postNotificationName:@"chang" object:nil];
    }else
    {
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-1"] forState:UIControlStateNormal];
        // 暂停
        [self.player pause];
    }
    // 改变状态
    self.isplay = !self.isplay;
}
- (void)full:(UIButton *)button
{
    if (self.isFull) {
        [self.fullButton setImage:[UIImage imageNamed:@"iconfont-fullscreen-exit"] forState:UIControlStateNormal];
        self.MVTableView.hidden = YES;
        self.playView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        self.playView.backgroundColor = [UIColor darkGrayColor];
        self.layer.frame = CGRectMake(0, 200, WIDTH, WIDTH / 16 * 9);
        self.playButton.frame = CGRectMake(5, 175 + 200, 35, 35);
        self.fullButton.frame = CGRectMake(WIDTH - 45, 175 + 200, 35, 35);
        self.placeImageView.hidden = YES;
    }else
    {
        [self.fullButton setImage:[UIImage imageNamed:@"iconfont-fullscreen"] forState:UIControlStateNormal];
        self.MVTableView.hidden = NO;
        self.playView.frame = CGRectMake(0, 0, WIDTH, WIDTH / 16 * 9);
        self.playView.backgroundColor = [UIColor whiteColor];
        self.layer.frame = CGRectMake(0, 0, WIDTH, WIDTH / 16 * 9);
        self.playButton.frame = CGRectMake(5, 175, 35, 35);
        self.fullButton.frame = CGRectMake(WIDTH - 45, 175, 35, 35);
        self.placeImageView.hidden = NO;
    }
    self.isFull = !self.isFull;
}
#pragma mark 懒加载
-(AVPlayer *)player{
    // 可以换集数
    if(!_player){
        AVPlayerItem *playerItem=[self getPlayItem];
        _player=[AVPlayer playerWithPlayerItem:playerItem];
    }
    return _player;
}
#pragma mark 播放的url转码
-(AVPlayerItem *)getPlayItem{
    //iOS9转码
    NSString * urlStr = [self.MVurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url=[NSURL URLWithString:urlStr];
    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
    return playerItem;
}
#pragma mark 解析数据
- (void)createTableViewData
{
    NSString *back = @"/similarity?utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&v=v8.1.0.2015071519&f=f168&mid=MI%2B2S&tid=0";
    NSString *url = [NSString stringWithFormat:@"http://api.dongting.com/sim/mv/%@%@",self.myId,back];
    NSLog(@"%@",url);
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        self.MVArr = [ZCMVPlayModel baseModelByArr:dic[@"data"]];
        for (NSInteger i = 0; i<self.MVArr.count; i++) {
            ZCMVPlayModel *model = self.MVArr[i];
            if(model.mvList.count == 0){
                [self.MVArr removeObjectAtIndex:i];
            }
        }
        [self.MVTableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"error = %@",error);
    }];
}
#pragma mark tableView实现
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.MVArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse=@"reuse";
    ZCMVPlayerTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell =[[ZCMVPlayerTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
    }
    ZCMVPlayModel *MVPlayModel = self.MVArr[indexPath.row];
    NSString *picUrl = MVPlayModel.mvList[0][@"picUrl"];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:picUrl]placeholderImage:[UIImage imageNamed:@"3187"]];
    cell.titleLabel.text = MVPlayModel.videoName;
    cell.detailLabel.text = MVPlayModel.singerName;
    return cell;
}
#pragma mark 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.placeImageView.hidden = YES;
    ZCMVPlayModel *MVPlayModel = self.MVArr[indexPath.row];
    self.MVurl = MVPlayModel.mvList[0][@"url"];
    self.myId = MVPlayModel.uId;
    NSString *videoName = [NSString stringWithFormat:@"%@ - %@",MVPlayModel.singerName,MVPlayModel.videoName];
    self.videoNameLabel.text = videoName;
    self.introducelabel.text = MVPlayModel.desc;
    [self createTableViewData];
    [self.MVTableView reloadData];
    [self.player replaceCurrentItemWithPlayerItem:[self getPlayItem]];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
